#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <string>
#include <signal.h>

// void Handler(int signo)
// {
//     int cnt = 5;
//     while(cnt--)
//     {
//         std::cout << "我来处理信号了: " << signo << std::endl;
//         sleep(1);
//     }
// }
void SetNonBlock(int fd)
{
    int n = ::fcntl(fd,F_GETFL);
    if (n < 0)
    {
        std::cerr << "获取文件描述符属性失败" << std::endl;
        exit(1);
    }
    ::fcntl(fd,F_SETFL,fd|O_NONBLOCK);
}

int main()
{
    SetNonBlock(0);
    // signal(2,Handler); 验证不了被信号终止的场景
    std::string enter_str = "Please Enter: ";
    while(true)
    {
        write(1,enter_str.c_str(),enter_str.size());
        char buffer[1024];
        int n = ::read(0,buffer,sizeof(buffer)-1);
        if (n > 0){
            buffer[n] = 0;
            std::cout << "client says# " << buffer << std::endl;
        }
        else if(n == 0){
            std::cout << "client quit" << std::endl;
            break;
        }
        else 
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK){
                std::cout << "用户还没有输入数据: " << std::endl;
                sleep(1);
                continue;
            }
            else if(errno == EINTR){
                std::cout << "被信号终止" << std::endl;
                sleep(1);
                continue;
            }
            else 
            {
                std::cout << "read error" << std::endl;
                break;
            }
        }
    }
    return 0;
}
